
package it.neokree.materialnavigationdrawermodule.util;

import ohos.agp.text.Font;
import ohos.app.Context;
import ohos.app.Environment;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.Resource;
import ohos.global.resource.ResourceManager;

import java.io.*;
import java.util.LinkedHashMap;

/**
 * Custom Typeface Manager for Roboto Fonts inside the drawer
 *
 * @since 2021-05-10
 */
public class TypefaceManager {
    private static final String ROBOTO_REGULAR = "Roboto-Regular.ttf";
    private static final String ROBOTO_MEDIUM = "Roboto-Medium.ttf";
    private final LinkedHashMap<String, Font> mCache;

    public TypefaceManager(Context context) {
        this.mCache = new LinkedHashMap<>();
    }

    public Font getRobotoRegular(Context context) {
        Font typeface = mCache.get(ROBOTO_REGULAR);
        if (typeface == null) {
            typeface = getTypeface(context, ROBOTO_REGULAR);
            mCache.put(ROBOTO_REGULAR, typeface);
        }
        return typeface;
    }

    public Font getRobotoMedium(Context context) {
        Font typeface = mCache.get(ROBOTO_MEDIUM);
        if (typeface == null) {
            typeface = getTypeface(context, ROBOTO_REGULAR);
            mCache.put(ROBOTO_REGULAR, typeface);
        }
        return typeface;
    }

    public static Font getTypeface(Context context, String name) {
        ResourceManager resManager = context.getResourceManager();
        RawFileEntry rawFileEntry = resManager.getRawFileEntry("resources/rawfile/" + name);
        Resource resource = null;
        try {
            resource = rawFileEntry.openRawFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        StringBuffer fileName = new StringBuffer(name);
        File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), fileName.toString());
        OutputStream outputStream = null;
        try {
            if (resource != null) {
                outputStream = new FileOutputStream(file);
                int index;
                byte[] bytes = new byte[1024];
                while ((index = resource.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, index);
                    outputStream.flush();
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (resource != null) {
                    resource.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        Font.Builder builder = new Font.Builder(file);
        return builder.build();
    }
}
